Fix #19127 — Improve error message for named inputs mismatch in Functional model#22356
Fix #19127 — Improve error message for named inputs mismatch in Functional model#22356pctablet505 wants to merge 2 commits intokeras-team:masterfrom
Functional model#22356Conversation
When a Functional model expects dict inputs (e.g., {'a': input_a, 'b':
input_b}) but receives a single tensor or a list/tuple with the wrong
count, the previous error was a generic 'expects N input(s), but
received M'. This gives no hint that the model expects named dict inputs.
Override _assert_input_compatibility in Functional to check for this
case early and provide a clear, actionable message: 'Model expects
inputs as a dict with the following keys: [keys]. Pass your data as
model.fit({...}).'
List/tuple inputs with matching length are still allowed through for
backward compatibility (with existing warning about struct mismatch).
Fixes keras-team#19127
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly improves the user experience when working with Keras Functional API models that expect named dictionary inputs. By introducing more specific error messages for input type mismatches, it helps users quickly understand and correct issues related to providing data in the wrong format, reducing debugging time and frustration. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request significantly improves the user experience by providing a more informative and actionable error message when a Functional model with named inputs receives an incorrect input type. This change aligns well with the Keras API design guidelines. The implementation in functional.py correctly identifies the input mismatch and raises a helpful ValueError, and the updated test in functional_test.py properly validates this new behavior. I have one minor suggestion to enhance the readability of the error message construction.
| keys = list(self._inputs_struct.keys()) | ||
| raise ValueError( | ||
| f'Model "{self.name}" expects inputs as a `dict` with ' | ||
| f"the following keys: {keys}. Instead received " | ||
| f"{type(inputs).__name__}. Pass your data as " | ||
| "`model.fit({" | ||
| + ", ".join(f"'{k}': ..." for k in keys) | ||
| + "}, ...)`." | ||
| ) |
There was a problem hiding this comment.
For better readability, you can construct the example string for the error message in a separate variable. This avoids using + for string concatenation within the f-string, making the code cleaner.
keys = list(self._inputs_struct.keys())
example_fit_kwargs = ", ".join(f"'{k}': ..." for k in keys)
raise ValueError(
f'Model "{self.name}" expects inputs as a `dict` with '
f"the following keys: {keys}. Instead received "
f"{type(inputs).__name__}. Pass your data as "
f"`model.fit({{{example_fit_kwargs}}}, ...)`."
)
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #22356 +/- ##
=======================================
Coverage 82.95% 82.95%
=======================================
Files 595 595
Lines 66040 66046 +6
Branches 10305 10308 +3
=======================================
+ Hits 54785 54790 +5
Misses 8639 8639
- Partials 2616 2617 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Fixes: #19127
This pull request improves the input validation logic for models with dictionary-based inputs in the Keras Functional API. The main change is to provide clearer error messages when users supply inputs in the wrong format, making it easier to diagnose and fix input-related issues. The corresponding test has also been updated to match the new error message.
Input validation improvements:
_assert_input_compatibilitymethod inModel(infunctional.py) to check for cases where the model expects a dictionary of inputs but receives a non-dictionary (like a list, tuple, or array). If a list or tuple of matching length is provided, it falls back to positional matching; otherwise, it raises a clearerValueErrorwith guidance on the expected input format.Testing updates:
test_bad_input_specinfunctional_test.pyto expect the new, more descriptive error message when a non-dictionary input is passed to a model expecting a dictionary.Problem
When a
Functionalmodel is built with dict inputs (e.g.keras.Input({"a": ..., "b": ...})), passing a plain array or list tomodel.fit()/model(...)raised a confusing error:"expects 2 input(s)". This message gave no hint that the model requires named dict inputs, making it very hard for users to diagnose the problem (see thread in #19127).Root Cause
Functional._assert_input_compatibilityunconditionally delegated to the parentModelimplementation, which only checks the input count. It had no awareness that its_inputs_structis adict, so the error path never mentioned dict/named inputs at all.Fix
Override
_assert_input_compatibilityinFunctionalto detect the mismatch early. If the model's input struct is adictbut the user passes a non-dict:ValueErrorthat names the expected keys and shows the correct calling syntax:Files Changed
keras/src/models/functional.py— override_assert_input_compatibilitywith dict-aware checkkeras/src/models/functional_test.py— update test to match new error text